/**
* 设备管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>设备管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="search-form">
      <el-form-item>
        <el-select
          size="small"
          v-model="formInline.productKey"
          placeholder="请选择产品"
        >
          <el-option label="所有产品" value=""></el-option>
          <el-option
            v-for="pro in products"
            :label="pro.name"
            :value="pro.id"
            :key="pro.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          size="small"
          v-model="formInline.state"
          placeholder="设备状态"
        >
          <el-option label="所有状态" value=""></el-option>
          <el-option label="在线" value="online"></el-option>
          <el-option label="离线" value="offline"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          size="small"
          v-model="formInline.group"
          placeholder="设备分组"
        >
          <el-option label="所有组" value=""></el-option>
          <el-option
            v-for="g in groups"
            :key="g.id"
            :label="g.name"
            :value="g.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          size="small"
          v-model="formInline.keyword"
          placeholder="输入关键字"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button size="small" icon="el-icon-plus" @click="createDevice"
          >创建</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="$store.state.loading"
      @selection-change="onSelecteChange"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column
        sortable
        prop="deviceId"
        label="设备ID"
        width="250"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        sortable
        prop="productKey"
        label="产品"
        width="100"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        sortable
        prop="deviceName"
        label="设备DN"
        width="240"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        sortable
        prop="group"
        label="分组"
        width="70"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-tag
            style="display: block; margin: 2px 0"
            v-for="g in scope.row.group"
            :key="g.id"
            size="mini"
            >{{ g.name }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        sortable
        prop="state"
        label="状态"
        width="80"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state.online" type="success" size="mini"
            >在线</el-tag
          >
          <el-tag v-if="!scope.row.state.online" type="danger" size="mini"
            >离线</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        sortable
        prop="createAt"
        label="创建时间"
        width="180"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <div>{{ scope.row.createAt | timestampToTime }}</div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="操作" min-width="240">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.nodeType == 0"
            size="mini"
            type="infor"
            @click="showChidrenDevices(scope.$index, scope.row)"
            >子设备</el-button
          >
          <el-button
            v-if="scope.row.nodeType != 0"
            disabled
            size="mini"
            type="infor"
            @click="goDeviceDetail(scope.$index, scope.row)"
            >子设备</el-button
          >
          <el-button
            size="mini"
            type="infor"
            @click="goDeviceDetail(scope.$index, scope.row)"
            >详情</el-button
          >
          <el-popconfirm
            title="确认要删除吗？"
            @confirm="deleteDevice(scope.$index, scope.row)"
            class="mg-left-10"
          >
            <el-button slot="reference" size="mini" plain type="danger"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <Pagination :data="formInline" @onPagePaging="search"></Pagination>

    <div>
      <el-select size="mini" v-model="targetGroup" placeholder="设备分组">
        <el-option label="请选择分组" value=""></el-option>
        <el-option
          v-for="g in groups"
          :key="g.id"
          :label="g.name"
          :value="g.id"
        ></el-option>
      </el-select>
      <el-button size="mini" class="mg-left-10" @click="addToGroup"
        ><i class="el-icon-edit"></i>添加到组</el-button
      >
      <el-button size="mini" class="mg-left-10" @click="delFromGroup"
        ><i class="el-icon-delete"></i>从组中移除</el-button
      >
    </div>

    <el-dialog title="创建设备" :visible.sync="showCreateDevice" width="400px">
      <el-form ref="form" :model="createForm" :rules="rules" label-width="80px">
        <el-form-item label="产品" prop="productKey">
          <el-select
            size="small"
            v-model="createForm.productKey"
            placeholder="请选择产品"
          >
            <el-option
              v-for="pro in products"
              :label="pro.name"
              :value="pro.id"
              :key="pro.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备DN" prop="deviceName">
          <el-input
            size="small"
            v-model="createForm.deviceName"
            placeholder="一般为设备mac"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitDeviceCreate" size="small"
            >立即创建</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 子设备列表 -->
    <el-dialog
      title="子设备列表"
      :visible.sync="chidrenDevicesVisiable"
      width="70%"
    >
      <el-table
        size="small"
        :data="gatewayChildren"
        highlight-current-row
        v-loading="$store.state.loading"
        border
        element-loading-text="拼命加载中"
        style="width: 100%"
      >
        <el-table-column align="center" type="index" width="60">
        </el-table-column>
        <el-table-column
          sortable
          prop="deviceId"
          label="设备ID"
          width="250"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="productKey"
          label="产品"
          width="120"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="deviceName"
          label="设备DN"
          width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="state"
          label="状态"
          width="80"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.state.online" type="success" size="mini"
              >在线</el-tag
            >
            <el-tag v-if="!scope.row.state.online" type="danger" size="mini"
              >离线</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          sortable
          prop="createAt"
          label="创建时间"
          width="180"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div>{{ scope.row.createAt | timestampToTime }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="操作" min-width="150">
          <template slot-scope="scope">
            <el-popconfirm
              title="确认要解除与网关的关联吗？"
              @confirm="unbindDevice(scope.$index, scope.row)"
            >
              <el-button slot="reference" size="mini" plain type="danger"
                >解绑</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  DeviceList,
  DeviceCreate,
  DeleteDevice,
  UnbindDevice,
  GatewayChildren,
  DeviceGroupList,
  GroupDeviceAdd,
  GroupDeviceRemove,
} from "../../api/deviceApi";
import { ProductList } from "../../api/productApi";
import Pagination from "../../components/Pagination";
export default {
  data() {
    return {
      loading: false, //是显示加载
      showCreateDevice: false,
      chidrenDevicesVisiable: false,
      title: "",
      formInline: {
        page: 1,
        size: 10,
        total: 0,
        productKey: "",
        keyword: "",
        state: "",
        group: "",
      },
      createForm: {
        productKey: "",
        deviceName: "",
      },
      rules: {
        productKey: [
          { required: true, message: "请选择产品", trigger: "blur" },
        ],
        deviceName: [
          { required: true, message: "请输入设备DN", trigger: "blur" },
        ],
      },
      products: [],
      listData: [],
      gatewayChildren: [],
      productMap: {},
      groups: [],
      targetGroup: "",
      selectedDevices: [],
    };
  },
  components: {
    Pagination,
  },
  created() {
    this.getdata(this.formInline);
  },
  methods: {
    getdata(parameter) {
      ProductList({ page: 1, size: 1000 }).then((res) => {
        this.products = res.data;
        let nodeTypeMap = {};
        res.data.forEach((p) => {
          this.productMap[p.id] = p.name;
          nodeTypeMap[p.id] = p.nodeType;
        });

        DeviceList(parameter).then((res) => {
          res.data.forEach((d) => {
            d["nodeType"] = nodeTypeMap[d.productKey];
            d.productKey = this.productMap[d.productKey];
          });

          this.listData = res.data;
          this.formInline.total = res.total;
        });
      });
      //取设备分组
      DeviceGroupList({ page: 1, size: 1000, name: "" }).then((res) => {
        this.groups = res.data;
      });
    },
    // 搜索事件
    search() {
      this.getdata(this.formInline);
    },
    createDevice() {
      this.showCreateDevice = true;
    },
    submitDeviceCreate() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          DeviceCreate(this.createForm).then(() => {
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
            });
            this.showCreateDevice = false;
            this.search();
          });
        }
      });
    },
    goDeviceDetail(index, row) {
      this.$router.push({
        path: "/device/DeviceDetail",
        query: {
          deviceId: row.deviceId,
        },
      });
    },
    deleteDevice(index, row) {
      DeleteDevice(row.deviceId).then(() => {
        this.search();
      });
    },
    unbindDevice(index, row) {
      UnbindDevice(row.deviceId).then(() => {
        this.search();
      });
    },
    showChidrenDevices(index, row) {
      GatewayChildren(row.deviceId).then((res) => {
        this.chidrenDevicesVisiable = true;

        res.forEach((d) => {
          d.productKey = this.productMap[d.productKey];
        });
        this.gatewayChildren = res;
      });
    },
    onSelecteChange(devices) {
      this.selectedDevices = devices;
    },
    addToGroup() {
      if (this.selectedDevices.length == 0 || !this.targetGroup) {
        this.$notify({
          title: "提示",
          message: "请选择设备或分组",
          type: "error",
        });
        return;
      }
      this.$confirm("确定将所选择设备添加到该组?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let devices = [];
          this.selectedDevices.forEach((d) => {
            devices.push(d.deviceId);
          });
          this.loading = true;
          GroupDeviceAdd(this.targetGroup, devices).then(() => {
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
            });
            setTimeout(() => {
              this.search();
            }, 300);
          });
        })
        .catch(() => {});
    },
    delFromGroup() {
      if (this.selectedDevices.length == 0 || !this.targetGroup) {
        this.$notify({
          title: "提示",
          message: "请选择设备或分组",
          type: "error",
        });
        return;
      }
      this.$confirm("确定将所选择设备从该组中移除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          let devices = [];
          this.selectedDevices.forEach((d) => {
            devices.push(d.deviceId);
          });
          GroupDeviceRemove(this.targetGroup, devices).then(() => {
            this.$notify({
              title: "成功",
              message: "移除成功",
              type: "success",
            });
            setTimeout(() => {
              this.search();
            }, 300);
          });
        })
        .catch(() => {});
    },
  },
};
</script>
